package fu.capstone.hanoicityguide.common.vgservice;

import java.util.ArrayList;

import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.attraction.AttractionBO;
import fu.capstone.hanoicityguide.business.bo.attraction.AttractionBOImp;
import fu.capstone.hanoicityguide.business.model.Attraction;
import fu.capstone.hanoicityguide.business.model.Category;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class VoiceGuidanceService extends Service {

	private ArrayList<Attraction> arrAttraction;
	private AttractionBO attractionBO;
	private MyLocationListener mylocationlister;
	private LocationManager locationManager;
	private static final String PROX_ALERT_INTENT = "ProximityAlert";
	private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1; // in
																		// Meters
	private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000; // in
																	// Milliseconds

	private static final long POINT_RADIUS = 300; // in Meters
	private static final long PROX_ALERT_EXPIRATION = -1; // -1 = never expire

	public static BroadcastReceiver mRegisterReceiver;

	public VoiceGuidanceService() {
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.v("Service", "Service started");
		
		String[] arrSorter = new String[5];
		arrSorter = getResources().getStringArray(R.array.sorter_items);
		attractionBO = new AttractionBOImp(this);
		arrAttraction = new ArrayList<Attraction>();

		// set filter all for listAttraction
		ArrayList<Category> listCategory = new ArrayList<Category>();
		listCategory = attractionBO.getListCategory("Attraction");

		String[] filterAll;
		filterAll = attractionBO.getListType(listCategory.get(0).getId());

		ArrayList<String> filterAtrraction = new ArrayList<String>();
		for (int i = 0; i < filterAll.length; i++) {
			filterAtrraction.add(filterAll[i]);
		}
		// ////////////////////////////////////////////////////////////////////
		arrAttraction = attractionBO.listAttraction(filterAtrraction,
				arrSorter[0]);

		// ------------------------------------------------
		// get the current location and implement location change listener
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mylocationlister = new MyLocationListener();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				MINIMUM_TIME_BETWEEN_UPDATE, MINIMUM_DISTANCECHANGE_FOR_UPDATE,
				mylocationlister);

		registerIntent();
		IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);

		mRegisterReceiver = new ProximityIntentReceiver();
		registerReceiver(mRegisterReceiver, filter);

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.v("Destroy Service", "destroy");
		unregisterReceiver(mRegisterReceiver);
		locationManager.removeUpdates(mylocationlister);
		locationManager = null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub

		Log.v("Service", "on start command");
		return Service.START_STICKY;

	}

	public void registerIntent() {
		for (int i = 0; i < arrAttraction.size(); i++) {
			arrAttraction.get(i).getGeo().getLatitude();
			arrAttraction.get(i).getGeo().getLongitude();
			setProximityAlert(arrAttraction.get(i).getGeo().getLatitude(),
					arrAttraction.get(i).getGeo().getLongitude(),
					// i+1,
					i, arrAttraction.get(i));
		}

	}

	private void setProximityAlert(double lat, double lon, int requestCode,
			Attraction attraction) {
		// 100 meter radius
		// float radius = 100f;

		// Expiration is 10 Minutes (10mins * 60secs * 1000milliSecs)
		// long expiration = -1;

		LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		Intent intent = new Intent(PROX_ALERT_INTENT);

		// -----------------------------------
		// put extra to notification
		Bundle placeInfo = new Bundle();
		placeInfo.putInt("RequestCodeID", requestCode);
		placeInfo.putString("PlaceName", attraction.getName());
		placeInfo.putInt("PlaceID", attraction.getId());

		// long registrationTime = System.currentTimeMillis();
		// placeInfo.putLong("RegistrationTime", registrationTime);
		intent.putExtra("PlaceInfo", placeInfo);
		// placeInfo.putInt("PlaceID", place.getID());
		// placeInfo.putDouble("PlaceLat", place.getLatitude());
		// placeInfo.putDouble("PlaceLon", place.getLongitude());

		PendingIntent pendingIntent = PendingIntent.getBroadcast(
				getApplicationContext(), requestCode, intent,
				PendingIntent.FLAG_CANCEL_CURRENT);

		locManager.addProximityAlert(lat, lon, POINT_RADIUS,
				PROX_ALERT_EXPIRATION, pendingIntent);

//		requestCode++;

	}

	public class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			// Location pointLocation = retrievelocation();
			// float distance = location.distanceTo(pointLocation);

			Log.v("My location", location.toString());

			// Toast.makeText(ProxAlertActivity.this,
			// "Distance from Point:" + distance, Toast.LENGTH_LONG)
			// .show();
		}

		public void onStatusChanged(String s, int i, Bundle b) {
		}

		public void onProviderDisabled(String s) {
		}

		public void onProviderEnabled(String s) {
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
